<?php

declare(strict_types=1);

namespace app\yperp\command;

use DateTime;
use Facebook\WebDriver\Exception\NoSuchWindowException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Fastposter\Client as FastposterClient;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;
use GuzzleHttp\Psr7\Utils;
use InvalidArgumentException;
use RuntimeException;
use think\Db;
use think\facade\Cache;

class suosi2 extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected $token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOiIlN0IlMjJhdmF0YXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRndld29yay5xcGljLmNuJTJGd3dwaWMzYXolMkY5OTU3ODZfTnc0YXFZZEZTamFHbmpVXzE3MTYyNzc3MzMlMkYwJTIyJTJDJTIyY29ycElkJTIyJTNBJTIyd3cyYjFhOGVkZGIzMjcyZmZiJTIyJTJDJTIyaW5kdXN0cnlUeXBlJTIyJTNBJTIybXl0eGwlMjIlMkMlMjJsb2dpblR5cGUlMjIlM0ElMjJub3JtYWwlMjIlMkMlMjJtZW1iZXJJZCUyMiUzQTE3NjA5Mjg5MjA1MjY1ODAxMTMlMkMlMjJtZW1iZXJOYW1lJTIyJTNBJTIyJUU2JTlEJThFJUU0JUI4JTk2JUU1JUI5JUIzJTIyJTJDJTIybW9iaWxlJTIyJTNBJTIyMTg5ODExNDAxMDElMjIlMkMlMjJvcmdJZCUyMiUzQTEwMDAxMCUyQyUyMm9yZ05hbWUlMjIlM0ElMjIlRTklOTUlQkYlRTglOTklQjklRUYlQkMlODglRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlRUYlQkMlODklMjIlMkMlMjJvcmdUeXBlJTIyJTNBJTIyZ2VuZXJhbCUyMiUyQyUyMnJlZ2lvbkNvZGUlMjIlM0ElMjIwMDAwMDAwMDAwMDAwMDAwMDAlMjIlMkMlMjJzaG9ydE5hbWUlMjIlM0ElMjIlRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlMjIlMkMlMjJ1c2VySWQlMjIlM0ExNzYwOTI4OTIwNTI2NTgwMTEzJTJDJTIydXNlck5hbWUlMjIlM0ElMjIlRTYlOUQlOEUlRTQlQjglOTYlRTUlQjklQjMlMjIlMkMlMjJ1c2VyVHlwZSUyMiUzQSUyMmVtcGxveWVlJTIyJTdEIiwidXNlcl9uYW1lIjoiMTAwMDEwOzE3NjA5Mjg5MjA1MjY1ODAxMTM7ZW1wbG95ZWU7bm9ybWFsIiwib3JnX2lkIjoxMDAwMTAsInNjb3BlIjpbImFsbCJdLCJleHAiOjE3MjQzNzY1MzYsImp0aSI6IjBjZTlhNmQ3LWIwNDgtNDlmZS05YjkwLTljOWM3YzlhODNlNCIsImNsaWVudF9pZCI6InByb2R1Y3Rpb24ifQ.oELIeFt774ZgV-NDlJarV3uC4iOM9tyc7OVeL_cHUSL6eQpQP5Xxpqns_CWuBLfRaimxrR6PLw-YRb421HIxc71z5UoEXaLTjANN0ly4EMwLpbR6IYyg02w6cetYg4lSwM4K98j0QmW5u3K-L2_YK5LwJZAP-XfapfUBwSNrh6A';

    // 群活码分组id
    public $grpup_ids = [
        '合肥' => '1793135207802933249',
        '成都' => '1784914950324916225',
        '绵阳' => '1784915354635022338',
        '重庆' => '1772508002709778434',
        '虹创' => '1763088628184178690',
    ];

    public $massage_tmpl_group_ids = [
        '合肥' => '1793135817821667329',
        '成都' => '1781208315725590529',
        '绵阳' => '1780811032366395393',
        '重庆' => '1772467865021087746',
        '虹创' => '1779833388841807874',
    ];
    protected function configure()
    {
        // 指令配置
        $this->setName('suosi')
            ->setDescription('批量设置群活码话术');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;
        try {

            $this->go();

        } catch (\Throwable $th) {
            dump($th->getMessage());
            dump($th->getTraceAsString());
        }
    }
    function go()
    {
        $type = '绵阳';
        $grpup_id = $this->grpup_ids[$type];

        $group_qr_list = $this->get_group_qr_list($grpup_id);

        foreach ($group_qr_list as $key => $value) {
            $image_ids = $this->upload_img($value['qrCode']);
            dump(['上传' => $image_ids]);
            $coverUrl = $image_ids['data']['groupId'];
            $response = $this->add_message_img_tmpl([
                'title' => $value['name'],
                'coverUrl' => $coverUrl,
                'columnIds' => $this->massage_tmpl_group_ids[$type]

            ]);
            dump(['添加' => $response]);
            if ($response['success']) {
                Db::table('dp_suosi_user1')->where(['dep_name' => $value['name']])->update(['msg_tmpl_qr_status' => 1]);
            }
        }
    }
    function require($url = '', $body, $method = 'POST', $headers = [])
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);

        $headers['authorization'] = $this->token;
        $headers['content-type'] = 'application/json;charset=utf-8';

        $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        dump($body);
        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }

    //获取所有群活码列表
    public function get_group_qr_list($groupid = '')
    {
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/findPageList';
        $response = $this->require($url, [
            "groupId" => (string) $groupid,
            "search" => (object) [],
            // "search" => (object) ['keyword' => "成都营门口店"],
            "pageNo" => 1,
            "pageSize" => 300
        ]);
        // dump($response);
        return $response['data']['dataSource'];

    }

    public function upload_img($image_url = '')
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);

        $image_url_array = explode('/', $image_url);
        $filename = (string) end($image_url_array);
        $url = 'https://m.suosishequ.com/gateway/file-center/web/file/uploadFileList?isSyncZip=1&urlZipLimit=1024&appCode=hsk&groupId=0&bizGroupId=0';

        $headers = [
            'authorization' => $this->token,
        ];
        $options = [
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => Utils::tryFopen($image_url, 'r'),
                    'filename' => $filename,
                ]
            ]
        ];
        $request = new Request('POST', $url, $headers);
        $res = $client->sendAsync($request, $options)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }

    public function add_message_img_tmpl($param)
    {
        $url = 'https://m.suosishequ.com/gateway/cms/web/news/level/add';
        $response = $this->require($url, [
            "title" => $param['title'],
            "coverUrl" => $param['coverUrl'],
            "qrCode" => [
                "qrSwitch" => false,
                "location" => []
            ],
            "columnIds" => [
                $param['columnIds']
            ],
            "qrSwitch" => 0,
            "location" => "{}",
            "appCode" => "hsk",
            "newsType" => 3
        ], 'POST', [
            'app-code' => 'notice-simple'
        ]);
        return $response;
    }
}


